package com.atguigu.spzx.manager.task;

import com.atguigu.spzx.common.utils.DateUtils;
import com.atguigu.spzx.manager.entity.OrderStatistics;
import com.atguigu.spzx.manager.mapper.OrderStatisticsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * <p>
 * OrderStatisticsTask
 * </p>
 *
 * @author flyduck
 * @since 2023/11/1
 */
@Slf4j
@Component
public class OrderStatisticsTask {

    @Autowired
    private OrderStatisticsMapper orderStatisticsMapper;

    //测试定时任务：每五秒一次
    //@Scheduled(cron = "0/5 * * * * ?")
    //public void testHello(){
    //    System.out.println(new Date().toInstant());
    //}

    //每天凌晨2点，查询前一天统计数据，把统计数据添加到order_statistics表
    @Scheduled(cron = "0 0 2 * * ?")
    //@Scheduled(cron = "0/10 * * * * ?")
    public void orderTotalAmountStatistics(){
        //1.获取前一天日期
        String previousDate = DateUtils.getYYYY_MM_DD(DateUtils.getPreviousDay(new Date()));
        log.info("====================汇总[{}]订单数据开始======================",previousDate);

        //2.根据前一天日期进行统计（分组）
        OrderStatistics orderStatistics = orderStatisticsMapper.getStatisticsByDate(previousDate);

        //3.把统计之后的数据添加到order_statistics表
        if (orderStatistics != null) {
            orderStatisticsMapper.insert(orderStatistics);
        }
        log.info("====================汇总[{}]订单数据结束======================",previousDate);
    }
}
